package com.fz.study.project.aop;

import com.alibaba.fastjson.JSONObject;
import com.fz.study.project.entity.Log;
import com.fz.study.project.service.ILogService;
import com.fz.study.project.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
//@Aspect
@Component
@RequiredArgsConstructor
public class LogAspect {

    private final HttpServletRequest request;
    private final ILogService logService;
    @Around("@annotation(com.fz.study.project.anno.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {

//        操作员id
//        获取token信息
        String jwt = request.getHeader("token");
//        解析token信息
        Claims claims = JwtUtils.parseJwt(jwt);
//        获取用户id
        String operateUser = (String) claims.get("username");
//        操作时间
        LocalDateTime operateTime = LocalDateTime.now();
//        操作类名
        String className = joinPoint.getTarget().getClass().getName();
//        操作方法名
        String methodName = joinPoint.getSignature().getName();
//        记录原始方法开始时间
        long begin = System.currentTimeMillis();
//        调用原始目标方法运行
        Object result = joinPoint.proceed();
//        记录原始方法结束时间
        long end = System.currentTimeMillis();
//        方法返回值
        String returnValue = JSONObject.toJSONString(result);
//        操作耗时
        Long costTime = end - begin;
        Log operateLog =
                new Log(null,operateUser,operateTime,className,methodName,returnValue,costTime);
        logService.save(operateLog);

        log.info("记录的日志对象{}",operateLog);

        return result;
    }
}
